import React from "react"
import {connect} from 'react-redux'
import {getUserList, SwitchToAnotherUser} from "../../../redux/actions/users";
import Breadcrumbs from "../../../components/@vuexy/breadCrumbs/BreadCrumb";
import {
  Card,
  CardBody,
  Input,
  Row,
  Col,
  UncontrolledDropdown,
  DropdownMenu,
  DropdownItem,
  DropdownToggle,
} from "reactstrap"
import {ContextLayout} from "../../../utility/context/Layout"
import "../../../assets/scss/plugins/tables/_agGridStyleOverride.scss"
import "../../../assets/scss/pages/users.scss"
import {ChevronDown} from "react-feather";
import {AgGridReact} from "ag-grid-react";
import Paginate from "../../../components/@vuexy/paginate";
import {setRequestParams} from "../../../redux/actions/users";
import FullSpinnerDimming from "../../../components/@vuexy/spinner/Full-spinner-dimming";
import {parseUnixTime} from '../../../helpers/utils'

class Users extends React.Component {

  state = {
    defaultColDef: {
      sortable: true,
    },
    rowSelection: 'single',
    columnDefs: [
      {
        headerName: "ID",
        field: "id",
        width: 150,
        filter: true,
      },
      {
        headerName: "Имя",
        field: "name",
        filter: true,
        width: 250,
      },
      {
        headerName: "Почта",
        field: "email",
        filter: true,
        width: 250
      },
      {
        headerName: "Role",
        field: "role.description",
        filter: true,
        width: 150
      },
      {
        headerName: "Зарегистрирован",
        field: "created_at",
        filter: true,
        width: 250,
        cellRendererFramework: params => {
          let date = parseUnixTime(params.value)
          return `${date.getDate()}.${date.getMonth() + 1}.${date.getFullYear()}`
        }
      }
    ]
  }

  componentDidMount() {
    this.props.getUserList(this.props.requestParams)
  }

  onGridReady = params => {
    this.gridApi = params.api
    this.gridColumnApi = params.columnApi
  }

  filterSize = val => {
    this.props.setRequestParams({"limit": val, "page": 1})
    this.props.getUserList({...this.props.requestParams, "limit": val, "page": 1})
  }

  updateSearchQuery = val => {
    this.props.setRequestParams({"search": val, "page": 1})
    this.props.getUserList({...this.props.requestParams, "search": val, "page": 1})
  }

  onPageChange = page => {
    this.props.setRequestParams({"page": page})
    this.props.getUserList({...this.props.requestParams, "page": page})
  }

  onSelectionChanged = () => {
    let selectedRows = this.gridApi.getSelectedRows();
    this.props.SwitchToAnotherUser(selectedRows[0].id || null)
  };

  render() {
    const {columnDefs, defaultColDef, pageSize} = this.state
    return (
      <React.Fragment>
        <Breadcrumbs
          breadCrumbTitle="Список пользователей"
          breadCrumbParent="Пользователи"
          breadCrumbActive="Список пользователей"
        />
        <Row className="app-user-list">
          <Col sm="12">
            <Card>
              <CardBody>
                { this.props.spinner.includes('users-list') && <FullSpinnerDimming /> }
                <div className="ag-theme-material ag-grid-table">
                  <div className="ag-grid-actions d-flex justify-content-between flex-wrap mb-1">
                    <div className="sort-dropdown">
                      <UncontrolledDropdown className="ag-dropdown p-1">
                        <DropdownToggle tag="div">
                          1 - {pageSize} из 150
                          <ChevronDown className="ml-50" size={15}/>
                        </DropdownToggle>
                        <DropdownMenu right>
                          <DropdownItem
                            tag="div"
                            onClick={() => this.filterSize(20)}
                          >
                            20
                          </DropdownItem>
                          <DropdownItem
                            tag="div"
                            onClick={() => this.filterSize(50)}
                          >
                            50
                          </DropdownItem>
                          <DropdownItem
                            tag="div"
                            onClick={() => this.filterSize(100)}
                          >
                            100
                          </DropdownItem>
                          <DropdownItem
                            tag="div"
                            onClick={() => this.filterSize(150)}
                          >
                            150
                          </DropdownItem>
                        </DropdownMenu>
                      </UncontrolledDropdown>
                    </div>
                    <div className="filter-actions d-flex">
                      <Input
                        className="w-100 mr-1 mb-1 mb-sm-0"
                        type="text"
                        placeholder="поиск..."
                        onChange={e => this.updateSearchQuery(e.target.value)}
                        value={this.props.requestParams.search}
                      />
                    </div>
                  </div>
                  {this.props.list !== null ? (
                    <ContextLayout.Consumer>
                      {context => (
                        <AgGridReact
                          defaultColDef={defaultColDef}
                          columnDefs={columnDefs}
                          rowData={this.props.list}
                          onGridReady={this.onGridReady}
                          colResizeDefault={"shift"}
                          animateRows={true}
                          pagination={false}
                          rowSelection={this.state.rowSelection}
                          onSelectionChanged={this.onSelectionChanged.bind(this)}
                        />
                      )}
                    </ContextLayout.Consumer>
                  ) : null}
                </div>
                <div className="mt-5 pt-5 pt-sm-2">
                  <Paginate pagination={this.props.meta.pagination} onPageChange={this.onPageChange}/>
                </div>
              </CardBody>
            </Card>
          </Col>
        </Row>
      </React.Fragment>
    )
  }
}

const mapStateToProps = state => (
  {
    requestParams: state.users.requestParams,
    list: state.users.list,
    meta: state.users.meta,
    spinner: state.helper.spinner
  }
)


export default connect(
  mapStateToProps,
  {
    setRequestParams,
    getUserList,
    SwitchToAnotherUser
  })(Users)
